#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>

/* 时间：6/22/2022 
 * 作者： panda_zhangs
 * 程序: 简单的 tcp 服务器通信demo；
 * 
 */
 
int main(){

    int sfd = socket(AF_INET,SOCK_STREAM,0);
    if(sfd<0){
        perror("socket create failed;");
        return -1;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    // addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    inet_pton(AF_INET,"127.0.0.1",&addr.sin_addr.s_addr);
    addr.sin_port = htons(8888);
    int ret = bind(sfd,(struct sockaddr *)&addr,sizeof(addr));
    // 给server 套接字绑定地址和端口；
    if(ret<0){
        perror("bind failed");
        close(sfd); // 退出前关闭套接字资源；
        return -1;
    }
    ret = listen(sfd,64);
    if(ret<0){
        perror("listen failed:");
        close(sfd);
        return -1;
    }
    int cfd = accept(sfd,NULL,NULL);
    int n=0;
    char buf[256],sstr[300];
    for(;;){
        memset(buf,0x00,sizeof(buf));
        memset(sstr,0x00,sizeof(sstr));
        int n = read(cfd,buf,sizeof(buf));
        if(n<=0||buf[0]=='\n'){
            printf("recv end,byte = [%d]\n",n);
            break;
        }
        snprintf(sstr,300,"server recv msg: %s",buf);
        printf("%s",sstr);
        write(cfd,sstr,strlen(sstr));
    }
    close(cfd);
    close(sfd);
    return 0;





}